using System.Threading;

namespace AsyncLibrary.Internal
{
  /// <summary><see cref="Thread"/> + <see cref="SynchronizedQueue{T}"/></summary>
  /// <typeparam name="T">operation type</typeparam>
  internal abstract class ThreadingCore<T>
  {
    private readonly SynchronizedQueue<T> _queue = new SynchronizedQueue<T>();

    public ThreadingCore(string threadName)
    {
      var thread = new Thread(Worker)
                        {
                          Name = threadName,
                          IsBackground = true,
                          Priority = ThreadPriority.BelowNormal
                        };
      thread.Start();
    }

    private void Worker()
    {
      while (true)
        Processing(_queue.Dequeue());
    }

    protected abstract void Processing(T operation);

    public void QueueWorkItem(T operation)
    {
      _queue.Enqueue(operation);
    }

    public void ClearQueue()
    {
      _queue.Clear();
    }
  }
}